java多线程系列10 阻塞队列模拟

接下来的几篇博客会介绍下juc包下的相关数据结构

包含queuelistmap

这篇文章主要模拟下阻塞队列。

下面是代码

import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;

public class MyBlockingQueue<T>  {

	private final LinkedList<T> queue = new LinkedList<>();
	private final AtomicInteger size = new AtomicInteger(0);
	private final Object lock = new Object();
	private final int maxSize ;
	public MyBlockingQueue(int maxSize) {
		this.maxSize = maxSize;
	}

	public void add(T t) {
		synchronized (lock) {
			while (size.get() == maxSize) {
				try {
					lock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			queue.add(t);
			size.incrementAndGet();
			lock.notifyAll();
		}

	}

	public T poll() {

		T result = null;
		synchronized (lock) {
			while (size.get() == 0) {
				try {
					lock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
			result = queue.removeFirst();
			size.decrementAndGet();
			lock.notifyAll();
		}
		return result;
	}
	public int getSize()
	{
		return size.get();
	}
	
	public static void main(String[] args) {
		final MyBlockingQueue<String> queue  = new MyBlockingQueue<>(1);
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				queue.add("h");
				queue.add("j");
				queue.add("h1");
				queue.add("j1");
				queue.add("h2");
				queue.add("j2");
			}
		}, "t1");
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					while(true)
					{
						Thread.sleep(1000);
						System.out.println("t2取走的元素为:" + queue.poll());
					}
				
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "t2");
		Thread t3 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					while(true)
					{
						Thread.sleep(1000);
						System.out.println("t3取走的元素为:" + queue.poll());
					}
				
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "t3");
		t1.start();
		t2.start();
		t3.start();
	
	}
}

  

posted on 2017-06-06 18:06  一只小蜗牛12138  阅读(152)  评论(0编辑  收藏  举报

导航